package com.zrrd._11_network.udp.no_01;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.util.Scanner;

/**
 * @author WanJl
 * @version 1.0
 * @title Receive
 * @description 接收端
 * @create 2023/10/28 21:34
 */
public class Receive {
    public void receive() {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入接收端端口号：");
        String portStr = sc.nextLine();
        int port = Integer.parseInt(portStr);
        DatagramSocket ds = null;
        while (true) {
            try {
                //1、创建接收端的Socket对象(DatagramSocket)
                ds = new DatagramSocket(port);
                //2、创建一个数据包，用于接收数据
                byte[] bytes = new byte[1024];
                DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length);
                //3、调用DatagramSocket对象的方法接收数据
                //在接收到数据之前，当前线程会处在阻塞状态，等待数据的接收。
                ds.receive(datagramPacket);
                //4、解析数据包，并把数据在控制台显示
                String s = new String(datagramPacket.getData(), 0, datagramPacket.getLength());
                System.out.println("接收到数据：" + s);

                if (s.equals("886")) {
                    System.out.println("数据接收结束...");
                    break;
                }
            } catch (SocketException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                //5、关闭接收端
                ds.close();
            }
        }
    }
}
